package yaty.lee.ssh2.action;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import yaty.lee.ssh2.bean.Admin;
import yaty.lee.ssh2.exception.ModelException;
import yaty.lee.ssh2.service.AdminService;
import yaty.lee.ssh2.util.JsonUtil;
import yaty.lee.ssh2.util.PageList;

import com.opensymphony.xwork2.ActionSupport;

public class AdminManager extends ActionSupport {
	private static final long serialVersionUID = 9009135591514415312L;
	private AdminService adminService;

	public String main() {
		return "success";
	}

	private int rows = 10;
	private int page = 1;
	private Admin like = new Admin();

	public void list() {
		try {
			JSONObject root = new JSONObject();
			PageList<Admin> list = adminService.list(like, (page - 1) * rows,
					rows);
			int count = list.getRows();
			root.put("page", page);
			root.put("total", count / rows + ((count % rows) > 0 ? 1 : 0));
			root.put("records", count);
			JSONArray rows = new JSONArray();
			for (Admin s : list) {
				rows.add(s, JsonUtil.config());
			}
			root.put("rows", rows);
			ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
			root.write(ServletActionContext.getResponse().getWriter());
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

	private Admin admin = new Admin();

	public String saveAdmin() throws ModelException {
		adminService.saveAdmin(this.admin);
		return "success";
	}

	public String modify() {
		try {
			adminService.modify(admin);
			return "success";
		} catch (ModelException e) {
			e.printStackTrace();
		}
		return "error";
	}

	private Integer id;

	public void load() {
		try {
			JSONObject root = new JSONObject();
			Admin adm = adminService.load(id);
			root.element("admin", adm, JsonUtil.config());
			ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
			root.write(ServletActionContext.getResponse().getWriter());
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

	public void setAdminService(AdminService adminService) {
		this.adminService = adminService;
	}

	public void setAdmin(Admin admin) {
		this.admin = admin;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public void setLike(Admin like) {
		this.like = like;
	}
}
